package com.lin.zoo.view;

import com.lin.zoo.util.DataBase;

import javax.swing.*;
import javax.swing.table.DefaultTableModel;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.sql.*;
import java.util.Vector;

public class FeederMasterPage {
    private JFrame frame;//新窗口
    private JButton addButton, setCardButton,setNumberButton,delButton;//设置雇佣按钮，辞退按钮，个人数据的输入
    private JTable jTable;//设置表格
    private DefaultTableModel mol;
    private JScrollPane scrollPane;//添加滚轮
    private JPanel panel;
    private JTextField jText=new JTextField("请在此输入修改的数据");
    private JLabel labAccount = new JLabel("用户名");

    private JTextField jtaText;
    private JLabel labPassword = new JLabel("密码");
    private JPasswordField jtb_text;
    private JButton btn_sign = new JButton("注册");

    private Vector<String> rowVector;
    private Vector<Vector<String>> dataVector;
    private Connection con;
    private PreparedStatement state;
    private ResultSet rs;

    private static int userid;

    public JLabel getLabAccount() {
        return labAccount;
    }

    public void setLabAccount(JLabel labAccount) {
        this.labAccount = labAccount;
    }

    public JTextField getJtaText() {
        return jtaText;
    }

    public void setJtaText(JTextField jtaText) {
        this.jtaText = jtaText;
    }

    public JLabel getLabPassword() {
        return labPassword;
    }

    public void setLabPassword(JLabel labPassword) {
        this.labPassword = labPassword;
    }

    public JPasswordField getJtb_text() {
        return jtb_text;
    }

    public void setJtb_text(JPasswordField jtb_text) {
        this.jtb_text = jtb_text;
    }

    public JButton getBtn_sign() {
        return btn_sign;
    }

    public void setBtn_sign(JButton btn_sign) {
        this.btn_sign = btn_sign;
    }

    public JButton getAddButton() {
        return addButton;
    }

    public void setAddButton(JButton addButton) {
        this.addButton = addButton;
    }

    public JButton getSetCardButton() {
        return setCardButton;
    }

    public void setSetCardButton(JButton setCardButton) {
        this.setCardButton = setCardButton;
    }

    public JButton getSetNumberButton() {
        return setNumberButton;
    }

    public void setSetNumberButton(JButton setNumberButton) {
        this.setNumberButton = setNumberButton;
    }

    public JButton getDelButton() {
        return delButton;
    }

    public void setDelButton(JButton delButton) {
        this.delButton = delButton;
    }

    public JTextField getjText() {
        return jText;
    }

    public void setjText(JTextField jText) {
        this.jText = jText;
    }


    public void createAndShowGUI() throws  SQLException{
        frame=new JFrame("饲养员信息管理系统");
        frame.setVisible(true);
        frame.setSize(1000,400);
        frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
        // 显示窗口
        frame.setResizable(false);
        //固定窗口大小不被修改
        frame.setLocationRelativeTo(null);
        //窗口处于中央
        rowVector= new Vector<>();
        rowVector.add("id");
        rowVector.add("身份证");
        rowVector.add("手机号码");
        rowVector.add("饲养员姓名");//添加列名称

        mol=new DefaultTableModel();
        try{
            con =DataBase.getCon();
            state = con.prepareStatement("select * from feeder");
            rs=state.executeQuery();

        }catch (ClassNotFoundException e) {
            System.out.println("数据读取错误"+this.getClass().getName());
        }//直接在view中调用了数据库，希望这个问题可以在日后想办法改变
        setData(rs);
        DataBase.close(state, con);
        jTable=new JTable(mol);
        jTable.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
        scrollPane=new JScrollPane(jTable);
        jTable.setRowHeight(50);
        frame.add(scrollPane,BorderLayout.CENTER);//添加滚轮
        init();//设置界面参数
        frame.add(panel,BorderLayout.SOUTH);

        getDelButton().addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                int seletedRow=jTable.getSelectedRow();
                seletedRow=jTable.convertRowIndexToModel(seletedRow);//选中的行
                Object id=jTable.getValueAt(seletedRow+0,0);//读取选中行的id
                Object name=jTable.getValueAt(seletedRow+0,3);//读取选中行的名字
                if(seletedRow !=-1){
                    mol.removeRow(seletedRow);
                }
                try{
                    con=DataBase.getCon();
                    state= con.prepareStatement("DELETE FROM user WHERE name=?");
                    state.setObject(1,name);
                    state.executeUpdate();
                    state = con.prepareStatement("DELETE FROM feeder WHERE id=?");
                    state.setObject(1,id);//删除选取行的饲养员信息
                    state.executeUpdate();

                    DataBase.close(state, con);//关闭连接
                } catch (SQLException | ClassNotFoundException ex) {
                    System.out.println("数据删除错误"+this.getClass().getName());
                }
                JOptionPane.showMessageDialog(null, "删除成功", null, JOptionPane.PLAIN_MESSAGE);
            }
        });

        getSetCardButton().addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                int seletedRow=jTable.getSelectedRow();//选中行
                seletedRow=jTable.convertRowIndexToModel(seletedRow);
                Object id=jTable.getValueAt(seletedRow+0,0);
                String card=jText.getText();
                jTable.setValueAt(card,seletedRow,1);//将修改后的数据重新绘制到新表以便查看
                jTable.repaint();
                jText.setText("请在此输入需要修改的数据");
                try{
                    System.out.println(id);
                    System.out.println(card);
                    con=DataBase.getCon();
                    state = con.prepareStatement("update feeder set card=? WHERE id=?");//修改feeder的身份证号
                    state.setObject(1,card);
                    state.setObject(2,id);
                    state.executeUpdate();
                    DataBase.close(state, con);

                }catch (SQLException | ClassNotFoundException ex) {
                    System.out.println("数据修改错误"+this.getClass().getName());
                }
                JOptionPane.showMessageDialog(null, "修改成功", null, JOptionPane.PLAIN_MESSAGE);
            }
        });

        getSetNumberButton().addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                int seletedRow=jTable.getSelectedRow();  //记住选中行
                seletedRow=jTable.convertRowIndexToModel(seletedRow);
                Object id=jTable.getValueAt(seletedRow+0,0);
                String number=jText.getText();
                jTable.setValueAt(number,seletedRow,2);   //将输入的信息修改后重新绘制新表
                jTable.repaint();
                jText.setText("请在此输入需要修改的数据");
                try{
                    System.out.println(id);
                    System.out.println(number);
                    con=DataBase.getCon();
                    state = con.prepareStatement("update feeder set number=? WHERE id=?");
                    state.setObject(1,number);
                    state.setObject(2,id);//修改选中行的手机号码
                    state.executeUpdate();
                    DataBase.close(state, con);

                }catch (SQLException | ClassNotFoundException ex) {
                    System.out.println("数据修改错误" + this.getClass().getName());
                }
                JOptionPane.showMessageDialog(null, "修改成功", null, JOptionPane.PLAIN_MESSAGE);
            }
        });
        //添加按钮监听
        getAddButton().addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                Vector<String> row=new Vector<String>();
                JFrame create =new JFrame("创建账号");//创建新的窗口，用于新账号的注册
                create.setVisible(true);
                create.setSize(600,450);

                create.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
                // 显示窗口
                create.setResizable(false);
                //固定窗口大小不被修改
                create.setLocationRelativeTo(null);
                //窗口处于中央
                labAccount.setSize(200,100);
                labAccount. setLocation(180,50);

                jtaText = new JTextField();
                jtaText.setSize(190,30);
                jtaText.setLocation(230,90);

                labPassword.setSize(200,100);
                labPassword.setLocation(180,105);

                jtb_text = new JPasswordField();
                jtb_text.setSize(190,30);
                jtb_text.setLocation(230,140);

                btn_sign.setSize(90,30);
                btn_sign.setLocation(280,200);//设置按钮的参数以及位置

                create.add(labAccount);
                create.add(labPassword);
                create.add(jtaText);
                create.add(jtb_text);
                create.add(btn_sign);
                create.setLayout(null);   //简单注册页面完成


                //注册按钮功能
                getBtn_sign().addActionListener(new ActionListener() {
                    @Override
                    public void actionPerformed(ActionEvent e) {
                        String username= getJtaText().getText();
                        String password=getJtb_text().getText();
                        //获取输入的信息
                        try{
                            con = DataBase.getCon();
                            //获取连接
                            String sql = "INSERT INTO user (name,password) VALUES (?,?)";
                            //插入数据的sql语句
                            state = con.prepareStatement(sql, Statement.RETURN_GENERATED_KEYS);
                            //执行sql插入语句
                            state.setString(1,username);//name
                            state.setString(2,password);//password
                            state.executeUpdate();
                            try (ResultSet rs1 = state.getGeneratedKeys()) {
                                if (rs1.next()) {
                                    userid = rs1.getInt(1);//储存注册用户的id，以便于feeder中账号相联系

                                }
                            }
                            JOptionPane.showMessageDialog(null, "注册成功", null, JOptionPane.PLAIN_MESSAGE);//弹出功能弹窗
                            create.setVisible(false);//注册完成关闭窗口


                        }catch (SQLException | ClassNotFoundException ex) {
                            System.out.println("注册失败" + this.getClass().getName());
                        }
                        //创建新的没有信息的feeder对象
                        try{
                            System.out.println(userid);
                            con=DataBase.getCon();
                            state=con.prepareStatement("INSERT INTO feeder (card,number,user_id) VALUES (?,?,?)", Statement.RETURN_GENERATED_KEYS);
                            state.setObject(1," ");
                            state.setObject(2," ");
                            state.setObject(3,userid);//完成新feeder的创建
                            state.executeUpdate();
                            try (ResultSet rs = state.getGeneratedKeys()) {
                                if (rs.next()) {
                                    String id = rs.getString(1);
                                    row.add(id);
                                    row.add(" ");
                                    row.add(" ");
                                    row.add(String.valueOf(userid));
                                    mol.addRow(row);//插入了空的表，可以使用修改功能修改数据
                                }
                            }
                        }catch (SQLException | ClassNotFoundException ex) {
                            System.out.println("数据写入错误" + this.getClass().getName());
                        }
                    }
                });

            }
        });
    }
    public void init(){
        panel=new JPanel();
        delButton=new JButton("删除饲养员账号");
        setNumberButton=new JButton("修改手机号码");
        setCardButton=new JButton("修改身份证号");
        addButton=new JButton("雇佣新饲养员");

        panel.setLayout(new GridLayout(1,1));

        panel.add(addButton);
        panel.add(delButton);
        panel.add(setCardButton);
        panel.add(setNumberButton);
        panel.add(jText);

    }
    public void setData(ResultSet rs) throws SQLException{
        dataVector= new Vector<>();
        while(rs.next()) {
            Vector<String> vector = new Vector<>();
            for (int i = 1; i <= 3; i++)//4代表列数
                vector.add(rs.getString(i));//添加数据库数据到vector

            try {
                con=DataBase.getCon();
                state=con.prepareStatement("select name from user where id=?");
                state.setObject(1,rs.getInt(4));
                state.executeQuery();
                ResultSet name=state.executeQuery();
                while(name.next())
                vector.add(name.getString(1));
            }catch (SQLException | ClassNotFoundException ex) {
                ex.printStackTrace();
            }
            DataBase.close(state,con);
            dataVector.add(vector);//添加vector数据到dataVector
        }
        mol.setDataVector(dataVector,rowVector);//最后将数据输入至mol

    }
}
